using System;
using System.Collections.Generic;
using System.Text;
using ThaiLanguageTools.DataStruct;

namespace ThaiLanguageTools
{
    public class SearchResult
    {
        public readonly QueryInfo Query;
        public List<XDictEntry> Entries = new List<XDictEntry>();

        public SearchResult(QueryInfo query, XDictEntry entry) 
        {
            Query = query;
            Entries.Add(entry);
        }

        /// <summary>
        /// Merge the other serch result into this one
        /// </summary>
        /// <param name="otherResult"></param>
        public void Merge(SearchResult otherResult)
        {
            if (!CanMerge(otherResult)) { throw new ArgumentException("Cannot merge " + this + " with: "+otherResult); }
            foreach (XDictEntry e in otherResult.Entries)
            {
                Entries.Add(e);
            }
        }

        public static List<SearchResult> MergeResults(List<SearchResult> input)
        {
            if (input.Count == 0) { return input; }

            List<SearchResult> rv = new List<SearchResult>();

            SearchResult cur = null;
            foreach (SearchResult inResult in input)
            {
                // First result
                if (cur == null)
                {
                    cur = inResult;
                    rv.Add(cur);
                    continue;
                }

                // All others
                if (cur.CanMerge(inResult))
                {
                    cur.Merge(inResult);
                }
                else
                {
                    cur = inResult;
                    rv.Add(cur);
                }
            }
            return rv;
        }


        public bool CanMerge(SearchResult otherResult)
        {
            if (Query.Text != otherResult.Query.Text) { return false; }

            String headWord = Entries[0].Word.Text;
            foreach (XDictEntry e in otherResult.Entries)
            {
                if (headWord != e.Word.Text) { return false; }
            }
            return true;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("/" + Query.Text + " ");
            sb.Append(Query.Probability + "/ ");
            sb.Append(Entries[0].Word.Text + " ->");

            foreach (XDictEntry e in Entries)
            {
                XWordInfo ft = e.FirstTranslation;
                if (ft == null && e.Definitions.Count > 0) { ft = e.Definitions[0]; }
                if (ft == null) { ft = new XWordInfo("n/a", "en"); }

                sb.Append("/" + e.Word.PartOfSpeech + ": " + ft.Text + " ");

                //if (ft != null) { sb.Append(" " + e.ToString() /*ft.ToString()*/); }
            }

            return sb.ToString();
        }
    }
}
